import numpy as np
import json

import matplotlib
import matplotlib.pyplot as plt


class Network(object):
    def __init__(self, num_of_weights):
        # 随机产生w的初始值
        # 为了保持程序每次运行结果的一致性，此处设置固定的随机数种子
        np.random.seed(0)
        self.w = np.random.randn(num_of_weights, 1)
        self.b = 0.

    def forward(self, x):
        z = np.dot(x, self.w) + self.b
        return z

    def loss(self, z, y):
        error = z - y
        num_samples = error.shape[0]
        cost = error * error
        cost = np.sum(cost) / num_samples
        return cost

    def gradient(self, x, y):
        z = self.forward(x)
        gradient_w = (z - y) * x
        gradient_w = np.mean(gradient_w, axis=0)
        gradient_w = gradient_w[:, np.newaxis]
        gradient_b = (z - y)
        gradient_b = np.mean(gradient_b)
        return gradient_w, gradient_b

    def update(self, gradient_w, gradient_b, eta=0.01):
        self.w = self.w - eta * gradient_w
        self.b = self.b - eta * gradient_b

    def train(self, x, y, iterations=100, eta=0.01):
        losses = []
        # 后一半训练量
        for i in range(iterations):
            z = self.forward(x)
            L = self.loss(z, y)
            gradient_w, gradient_b = self.gradient(x, y)
            self.update(gradient_w, gradient_b, eta)
            losses.append(L)
            if (i + 1) % 10 == 0:
                print('iter {}, loss {}'.format(i, L))

        return losses

    # 随机梯度下降法，适用于大规模数据集
    def train_random(self, training_data, num_epochs, batch_size=10, eta=0.01):
        n = len(training_data)
        losses = []
        for epoch_id in range(num_epochs):
            # 在每轮迭代开始之前，将训练数据的顺序随机打乱
            # 然后再按每次取batch_size条数据的方式取出
            np.random.shuffle(training_data)
            # 将训练数据进行拆分，每个mini_batch包含batch_size条的数据
            mini_batches = [training_data[k:k + batch_size] for k in range(0, n, batch_size)]
            for iter_id, mini_batch in enumerate(mini_batches):
                # print(self.w.shape)
                # print(self.b)
                x = mini_batch[:, :-1]
                y = mini_batch[:, -1:]
                a = self.forward(x)
                loss = self.loss(a, y)
                gradient_w, gradient_b = self.gradient(x, y)
                self.update(gradient_w, gradient_b, eta)
                losses.append(loss)
                print('Epoch {:3d} / iter {:3d}, loss = {:.4f}'.
                      format(epoch_id, iter_id, loss))

        return losses

def load_data():
    # 从文件导入数据
    datafile = "data/housing.data"
    data = np.fromfile(datafile, sep=' ')

    # 每条数据包括14项，其中前面13项是影响因素，第14项是相应的房屋价格中位数
    feature_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE',
                     'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']
    feature_num = len(feature_names)

    # 将原始数据进行Reshape，变成[N, 14]这样的形状
    data = data.reshape([data.shape[0] // feature_num, feature_num])

    # 将原数据集拆分成训练集和测试集
    # 这里使用80%的数据做训练，20%的数据做测试
    # 测试集和训练集必须是没有交集的
    ratio = 0.8
    offset = int(data.shape[0] * ratio)
    training_data = data[:offset]

    # 计算训练集的最大值，最小值
    maximums, minimums = training_data.max(axis=0), \
        training_data.min(axis=0)

    # 对数据进行归一化处理
    for i in range(feature_num - 1):  # 只对影响因素进行归一化处理，最后一列是房屋价格中位数不需要归一化
        data[:, i] = (data[:, i] - minimums[i]) / (maximums[i] - minimums[i])

    # 训练集和测试集的划分比例
    training_data = data[:offset]
    test_data = data[offset:]
    return training_data, test_data

# def granient_descent(X, y, w, b, learning_rate, epochs):
#     m = X.shape[0]
#     print("Number of training examples:", m)
#     cost_history = []
#
#     for epoch in range(epochs):
#         y_hat = np.dot(X, w) + b
#         loss = y_hat - y
#
#         cost = np.sum(loss ** 2) / (2 * m)
#         cost_history.append(cost)
#
#         dw = (1 / m) * np.dot(X.T, loss)
#         db = (1 / m) * np.sum(loss)
#
#         w -= learning_rate * dw
#         b -= learning_rate * db
#
#     return w, b, cost_history

def main():
    # 获取数据
    train_data, test_data = load_data()

    # 创建网络
    net = Network(13)
    # 启动训练

    losses = net.train_random(train_data, num_epochs=100, batch_size=10, eta=0.01)

    # 画出损失函数的变化趋势
    plot_x = np.arange(len(losses))
    plot_y = np.array(losses)
    plt.plot(plot_x, plot_y)
    plt.show()

    # 记录程序结束时间
    end_time = time.time()
    # 输出程序运行时间
    print("程序运行时间：%f 秒" % (end_time - start_time))

    # # 画出损失函数的变化趋势
    # plot_x = np.arange(num_iterations)
    # plot_y = np.array(losses)
    # plt.plot(plot_x, plot_y)
    # plt.show()


if __name__ == '__main__':
    print("----------------program started----------------")
    # 记录程序开始时间
    import time
    start_time = time.time()
    main()

    # training_data, testing_data = load_data()
    # x = training_data[:, :-1]
    # x_test = testing_data[:, :-1]
    # y_test = testing_data[:, -1]
    # y = training_data[:, -1]
    # w = np.zeros(x.shape[1])
    # b = 0.
    # learning_rate = 0.01
    # epochs = 1000
    # w, b, cost_history = granient_descent(x, y, w, b, learning_rate, epochs)
    # print("w:", w)
    # print("b:", b)
    #
    # y_pred = np.dot(x_test, w) + b
    # mse = np.mean((y_pred - y_test) ** 2)
    # print(f"测试集的MSE为：{mse}")
    #
    # print("-----------------program ended-----------------")
